<template>
  <div class="selectUser">
    <el-drawer title="选择范围" @close="filterText = ''" :visible.sync="isPop" append-to-body :modal="false" custom-class="selectDrawer">
      <div class="block">
        <el-input placeholder="输入关键字进行过滤" v-model="filterText"></el-input>
      </div>
      <div class="tree">
        <el-tree @check="nodeClick" :data="treeData" id="el-tree" show-checkbox node-key="id" :default-expanded-keys="['00000000-0000-0000-0000-000000000000']" :render-content="renderContent" highlight-current ref="tree" :default-checked-keys="defaultCheckedKeys" :filter-node-method="filterNode" :props="defaultProps"> </el-tree>
      </div>
      <div class="footer">
        <el-button type="primary" class="clearBtn" @click="onClear">取消</el-button>
        <el-button type="primary" class="queryBtn" @click="confirmSelect">确定</el-button>
      </div>
    </el-drawer>
    <el-button type="primary" class="queryBtn" @click="isPop = true">{{ title || "选择范围" }}</el-button>
    <span v-if="!isHide" style="margin-left: 10px" v-html="strName"></span>
    <!-- 编辑时进入出发 -->
    <el-tree v-show="false" :data="treeData" node-key="id" ref="tree" :default-checked-keys="defaultCheckedKeys" :props="defaultProps"></el-tree>
  </div>
</template>
<script>
import { mapTreeAddIcon } from "@/util/util";
import { mapState } from "vuex";
export default {
  name: "selectUser",
  props: {
    selectedList: Array,
    isHide: Boolean,
    title: String,
    isLow: Boolean,
    isNewLow: Boolean,
    authType: Number,
    enterType: Number,
  },
  data() {
    return {
      isPop: false,
      defaultProps: {
        children: "childrens",
        label: "name",
      },
      filterText: "",
      treeData: [],
      strName: "",
      defaultCheckedKeys: [], // 默认勾选值
    };
  },
  watch: {
    authType: {
      immediate: true,
      handler() {
        this.getUsersList();
      },
    },
    filterText(val) {
      this.$refs.tree.filter(val);
    },
    defaultCheckedKeys(newVal, oldVal) {
      this.$nextTick(() => {
        if (newVal.length && !this.isHide) this.confirmSelect();
      });
    },
  },
  computed: {
    ...mapState({
      UserInfo: (state) => state.common.UserInfo,
      usersList: (state) => state.common.usersList,
    }),
  },
  methods: {
    nodeClick(data) {
      console.log(data, "data");
      if (!data.isExistEmployee && this.authType == 1) {
        // debugger;
        // let keys = this.$refs.tree.getCheckedKeys();
        // const index = keys.findIndex((m) => m == data.id);
        // if (index > -1) {
        this.$refs.tree.setChecked(data, false);
        this.$message.warning("当前部门无员工，无法勾选！");
        //   this.defaultCheckedKeys = keys.splice(index, 1);
        // }
      }
    },
    onClear() {
      this.isPop = false;
    },

    filterNode(value, data) {
      if (!value) return true;
      return data.name.indexOf(value) !== -1;
    },

    renderContent(h, { node, data, store }) {
      return (
        <span class="custom-tree-node">
          <img width="15px" src={data.icons} />
          <span title={node.label} style="margin-left:5px;font-size: 12px;position: relative;top: -1px;">
            {node.label.length > 20 ? node.label.slice(0, 20) + "..." : node.label}
          </span>
        </span>
      );
    },

    handleData(data, parentObj = {}) {
      // 关联父子数据  1   1-1   1-1-1    1-1-1-1   n-n-n-n
      data.map((item, index) => {
        if (parentObj.relatedId) {
          item.relatedId = parentObj.relatedId + `-${index + 1}`;
        } else {
          item.relatedId = index + 1 + "";
        }
        if (this.authType == 3) {
          item.childrens = item.childrens.filter((c) => c.type !== 3);
        }
        if (item.childrens && item.childrens.length) {
          this.handleData(item.childrens, item);
        }
        // if (this.enterType == 1) {
        //   item.disabled = !item.isExistEmployee;
        // }
      });
      return data;
    },

    confirmSelect() {
      let handleAfterNode = this.getHigherCheckedNodes(this.$refs.tree.store);
      handleAfterNode.forEach((item) => {
        if (item.type == 0) item.id = this.UserInfo.ccompanyId;
      });
      this.selected(handleAfterNode);
      // 仅人员
      if (this.isNewLow) handleAfterNode = this.getLowCheckedNodes(this.authType === 3);
      else if (this.isLow) handleAfterNode = this.getLowCheckedNodes();
      console.log(handleAfterNode, "handleAfterNode");
      this.$emit("getSelectedNode", handleAfterNode);
      this.$emit("update:selectedList", handleAfterNode);
    },

    /** 获取最高层节点 */
    getHigherCheckedNodes(store) {
      const checkedNodes = [];
      const traverse = function (node) {
        const childNodes = node.root ? node.root.childNodes : node.childNodes;
        childNodes.forEach((child) => {
          if (child.checked) {
            checkedNodes.push(child.data);
          }
          if (child.indeterminate) {
            traverse(child);
          }
        });
      };
      traverse(store);
      return checkedNodes;
    },

    getLowCheckedNodes(bol) {
      let handleAfterNode = this.$refs.tree.getCheckedNodes();
      const userArr = bol ? handleAfterNode.filter((item) => item.type == 2) : handleAfterNode.filter((item) => item.type == 3);
      return userArr;
    },

    // 调用
    selected(e) {
      // 定义范围名称
      let companyArr = e.filter((item) => item.type === 0);
      if (companyArr.length !== 0) {
        this.strName = `您已选<span class="tep-style" >全公司</span>；`;
      } else {
        let customArr = e.filter((item) => item.type === 1);
        let depmArr = e.filter((item) => item.type === 2);
        let userArr = e.filter((item) => item.type === 3);
        let strName = `${this.tempHtml(customArr, "公司")}${this.tempHtml(depmArr, "部门")}${this.tempHtml(userArr, "员工")}`;
        if (strName.length === 0) {
          this.strName = "";
        } else {
          this.strName = "您已选" + strName;
        }
      }
      this.onClear();
    },

    tempHtml(arr, str) {
      if (arr.length === 0) return "";
      if (arr.length <= 2) return `<span class="tep-style" >${this.sliceStrTwo(arr)}</span>${str}；`;
      return `<span class="tep-style" >${this.sliceStrTwo(arr)}</span>等<span class="tep-style" >${arr.length}</span>个${str}；`;
    },

    sliceStrTwo(arr) {
      arr = arr.slice(0, 2);
      if (arr.length === 0) {
        return "";
      }
      if (arr.length === 1) {
        return arr[0].name;
      }
      if (arr.length === 2) {
        return `${arr[0].name}、${arr[1].name}`;
      }
    },

    async getUsersList() {
      // authType  2部门人员树   3部门树  1员工GetEmployeeTree
      const { data } = await this.$api[this.authType == 1 ? "optionsManage" : "publicApi"][this.authType == 1 ? "GetEmployeeTree" : "GetSubCompanyView"]();
      console.log(data, "data----------");
      // console.log(data.data, this.handleData(data.data));
      this.treeData = JSON.parse(JSON.stringify(mapTreeAddIcon(this.handleData(this.authType == 1 ? data.data : data.data.childrens))));
      this.updateDefaultCheckKeys();
    },

    treeDataGetUser(data) {
      // tree扁平化
      return data.reduce((p, c) => p.concat([c], this.treeDataGetUser(c.childrens || [])), []);
    },

    /** 设置默认值 */
    updateDefaultCheckKeys(arr = this.selectedList) {
      if (!this.selectedList) {
        return;
      }
      console.log("updateDefaultCheckKeys", this.selectedList);
      this.defaultCheckedKeys = arr.map((item) => item.dataId || item.userId || item.id); //已选中员工
      const treeFlat = this.treeDataGetUser(this.treeData);
      // this.treeData = JSON.parse(JSON.stringify(this.usersList));
      if (this.isHide) {
        arr.forEach((item) => {
          console.log(item);
          this.getCompleteData(this.treeData, item.userId, true);
        });
      } else {
        arr.forEach((item) => {
          item.type = item.dataType;
          const { name = "" } = this.getCompleteData(this.treeData, item.dataId) || {};
          item.name = name;
        });
        this.selected(arr);
      }
    },

    /** 递归对应参数 */
    getCompleteData(arr, id, isDisabled) {
      const len = arr.length;
      let o = "";
      let parent = "";
      for (let i = 0; i < len; i++) {
        const item = arr[i];
        if (item.id == id) o = item;
        else if (item?.childrens?.length) {
          parent = item;
          o = this.getCompleteData(item.childrens, id, isDisabled);
        }
        if (o) {
          if (isDisabled) {
            o.disabled = true;
            const obj = parent?.childrens?.find((item) => !item.disabled);
            if (!obj && parent) parent.disabled = true;
          }
          return o;
        }
      }
    },
  },
  mounted() {},
};
</script>
<style lang="less" scoped>
:deep(.tep-style) {
  color: #31a2f2;
}
</style>
<style lang="less">
.selectDrawer {
  .el-drawer__header {
    margin: 0;
    padding: 6px 20px;
    background: #f4f9fe;
    color: #333;
    span {
      font-size: 12px;
    }
  }
  .el-drawer__close-btn {
    font-size: 16px;
  }
  .el-drawer__body {
    display: flex;
    // margin-bottom: 15px;
    flex-direction: column;
    justify-content: space-between;
    align-items: center;
  }
  .block {
    display: flex;
    align-items: center;
    width: 100%;
    .el-input {
      flex: 1;
      font-size: 12px;
    }
    .el-button {
      padding-left: 20px;
    }
    padding: 20px;
  }
  .tree {
    width: 100%;
    padding: 0 20px;
    height: 100%;
    overflow: auto;
    margin-bottom: 20px;
  }
  .footer {
    width: 100%;
    display: flex;
    justify-content: center;
    align-items: center;
    border-top: 1px solid #ccc;
    padding: 20px 0;
  }
}
</style>
